package com.regentsoft.cloudback.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.regentsoft.cloudback.base.BaseResp;
import com.regentsoft.cloudback.base.ResponseCode;
import com.regentsoft.cloudback.operateAdmin.util.SysAdminTokenManager;
import com.regentsoft.cloudback.util.JsonUtil;
/**
 * 运营管理后台登录拦截器
 * @author czd
 *
 * @date 2017年11月29日
 *
 * @version 1.0
 */
public class OperateInterceptor extends HandlerInterceptorAdapter{
	 private final SysAdminTokenManager tokenManager;

	    private final String TOKEN = "token";

	    public OperateInterceptor(SysAdminTokenManager tokenManager) {
	        this.tokenManager = tokenManager;
	    }

	    @Override
	    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
	        String token = request.getParameter(TOKEN);
	        if (token == null) {
	            respError(response);
	            return false;
	        }
	        	
	        boolean exist =  tokenManager.exists(token);
	        if (!exist){
	            respError(response);
	            return false;
	        }
	        return true;
	    }

	    private void respError(HttpServletResponse response) throws IOException {
	        response.setStatus(HttpServletResponse.SC_OK);
	        response.setContentType("text/html;charset=UTF-8");
	        BaseResp resp = new BaseResp();
	        resp.setCode(ResponseCode.NOTLOGIN);
	        resp.setMessage("尚未登录");
	        PrintWriter writer = response.getWriter();
	        writer.write(JsonUtil.toJsonStr(resp));
	        writer.close();
	    }
}
